package com.nefits.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLUtil {
     public static String getValue(String key, String path){
    	 String value = null;
    	 try {
    		 
				File f = new File(path);    
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    
				DocumentBuilder builder = factory.newDocumentBuilder();    
				Document doc = builder.parse(f);    

				
				Element rootElement = doc.getDocumentElement();
				NodeList children = rootElement.getChildNodes();
				int childSize = children.getLength();

				for (int i = 0; i < childSize; i++) {
				    Node childNode = children.item(i);

				    if (childNode instanceof Element) {
				        Element child = (Element) childNode;

				        final String nodeName = child.getNodeName();

				        if ("info".equals(nodeName)) {
				            String nodeKey = child.getAttribute("key");
				            if(nodeKey != null && !nodeKey.equals("") && nodeKey.equals(key)){
				            	value = child.getAttribute("value");
					            System.out.println("key: "+key+"  value:"+value);
				            }
				            
				        }   
				    }
				}
	
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return value;
     }
     
     public static Map getValue(Map<String, String> map, String path){
    	 if(map == null)
    		 return null;
    	 String value = null;
    	 try {
    		 
				File f = new File(path);    
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    
				DocumentBuilder builder = factory.newDocumentBuilder();    
				Document doc = builder.parse(f);    

				
				Element rootElement = doc.getDocumentElement();
				NodeList children = rootElement.getChildNodes();
				int childSize = children.getLength();
				Set keys = map.keySet();
	    		for(Iterator<String> it = keys.iterator(); it.hasNext(); ){
	    			 String key = it.next();
	    			 for (int i = 0; i < childSize; i++) {
	 				    Node childNode = children.item(i);

	 				    if (childNode instanceof Element) {
	 				        Element child = (Element) childNode;

	 				        final String nodeName = child.getNodeName();

	 				        if ("info".equals(nodeName)) {
	 				            String nodeKey = child.getAttribute("key");
	 				            if(nodeKey != null && !nodeKey.equals("") && nodeKey.equals(key)){
	 				            	value = child.getAttribute("value");
	 				            	map.put(key, value);
	 					            System.out.println("key: "+key+"  value:"+value);
	 				            }
	 				            
	 				        }   
	 				    }
	 				}
	    		}
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return map;
     }
     
     public static Map<String, String> getAll(String path){
    	 Map<String, String> map = new Hashtable<String, String>();
    	 try {
    		 
				File f = new File(path);    
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    
				DocumentBuilder builder = factory.newDocumentBuilder();    
				Document doc = builder.parse(f);    

				
				Element rootElement = doc.getDocumentElement();
				NodeList children = rootElement.getChildNodes();
				int childSize = children.getLength();

				for (int i = 0; i < childSize; i++) {
				    Node childNode = children.item(i);

				    if (childNode instanceof Element) {
				        Element child = (Element) childNode;

				        final String nodeName = child.getNodeName();

				        if ("info".equals(nodeName)) {
				            String nodeKey = child.getAttribute("key");
				            String value = child.getAttribute("value");
				            map.put(nodeKey, value);
				        }   
				    }
				}
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	 return map;
    	 
     }
     
     public static String setValue(String key, String value, String path){
    	 
    	 try {
    		 
				File f = new File(path);    
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    
				DocumentBuilder builder = factory.newDocumentBuilder();    
				Document doc = builder.parse(f);    

				
				Element rootElement = doc.getDocumentElement();
				NodeList children = rootElement.getChildNodes();
				int childSize = children.getLength();

				for (int i = 0; i < childSize; i++) {
				    Node childNode = children.item(i);

				    if (childNode instanceof Element) {
				        Element child = (Element) childNode;

				        final String nodeName = child.getNodeName();

				        if ("info".equals(nodeName)) {
				            String nodeKey = child.getAttribute("key");
				            if(nodeKey != null && !nodeKey.equals("") && nodeKey.equals(key)){
				            	child.setAttribute("value",value);
				            }
				            
				        }   
				    }
				}
				//保存xml文件
	            TransformerFactory transformerFactory=TransformerFactory.newInstance();
	            Transformer transformer=transformerFactory.newTransformer();
	            DOMSource domSource=new DOMSource(doc);
	            //设置编码类型
	            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
	            StreamResult result=new StreamResult(new FileOutputStream(path));
	            //把DOM树转换为xml文件
	            transformer.transform(domSource, result);

			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return value;
     }
     
     public static boolean setValue(Map map, String path){
    	 boolean rat = true;
    	 if(map != null){
    		 Set keys = map.keySet();
    		 for(Iterator<String> it = keys.iterator(); it.hasNext(); ){
    			 String key = it.next();
    			 String value = (String)map.get(key);
    			 try {
    	    		 
    					File f = new File(path);    
    					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    
    					DocumentBuilder builder = factory.newDocumentBuilder();    
    					Document doc = builder.parse(f);    

    					
    					Element rootElement = doc.getDocumentElement();
    					NodeList children = rootElement.getChildNodes();
    					int childSize = children.getLength();

    					for (int i = 0; i < childSize; i++) {
    					    Node childNode = children.item(i);

    					    if (childNode instanceof Element) {
    					        Element child = (Element) childNode;

    					        final String nodeName = child.getNodeName();

    					        if ("info".equals(nodeName)) {
    					            String nodeKey = child.getAttribute("key");
    					            if(nodeKey != null && !nodeKey.equals("") && nodeKey.equals(key)){
    					            	child.setAttribute("value",value);
    					            }
    					            
    					        }   
    					    }
    					}
    					//保存xml文件
    		            TransformerFactory transformerFactory=TransformerFactory.newInstance();
    		            Transformer transformer=transformerFactory.newTransformer();
    		            DOMSource domSource=new DOMSource(doc);
    		            //设置编码类型
    		            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    		            StreamResult result=new StreamResult(new FileOutputStream(path));
    		            //把DOM树转换为xml文件
    		            transformer.transform(domSource, result);

    				} catch (ParserConfigurationException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    					rat = false;
    				} catch (SAXException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    					rat = false;
    				} catch (Exception e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    					rat = false;
    				}
    		 }
    	 }
    	 
    	 return rat;
     }
     //String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/WEB-INF/classes/");
     public static void main(String[] args) {
 		// TODO Auto-generated method stub
    	 //File f = new File("F:\\config.xml"); 
    	 XMLUtil xml = new XMLUtil();
    	 xml.setValue("storename","李宁1","C:\\config.xml");
    	 int i = 0;
     
 	}
}
